package com.huxiaohui.ssbx.utils;

import cn.hutool.core.util.ObjectUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.web.socket.WebSocketSession;

import java.time.Duration;

public class SessionHolder {
    private static final Cache<String, WebSocketSession> sessionHandler = Caffeine.newBuilder()
            .expireAfterAccess(Duration.ofMinutes(10))
            .build();

    public static boolean put(String id, WebSocketSession session) {
        if (ObjectUtil.isEmpty(id) || ObjectUtil.isNull(session)) {
            return false;
        }
        sessionHandler.put(id, session);
        return true;
    }

    public static WebSocketSession get(String id) {
        if (ObjectUtil.isEmpty(id)) {
            return null;
        }
        return sessionHandler.getIfPresent(id);
    }


    public static void remove(String id) {
        if (ObjectUtil.isEmpty(id)) {
            return;
        }
        sessionHandler.invalidate(id);
    }

}
